import React from 'react';
import { Spin, message } from 'antd';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import { EditorState, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import htmlToDraft from 'html-to-draftjs';
import request from '@/utils/umiRequest';
import './index.less';

export default class ArticleDetail extends React.Component {
  state = {
    editorState: null,
    articleTitle: '',
    initLoading: true,
  };

  async componentWillMount() {
    this.setState({ initLoading: true });
    const id = this.props.location.state.id;
    const result = await request(`/icoded/article/info/${id}`, {
      method: 'GET',
    });
    const { success = false, msg = '', data = {} } = result || {};
    !success && message.error(msg || '获取文章详情失败！');
    const { articleHtml, articleTitle } = data || {};

    const blocksFromHtml = htmlToDraft(articleHtml);
    const { contentBlocks, entityMap } = blocksFromHtml;
    const contentState = ContentState.createFromBlockArray(
      contentBlocks,
      entityMap,
    );

    this.setState(
      {
        articleTitle,
        editorState: EditorState.createWithContent(contentState),
      },
      () => {
        this.setState({ initLoading: false });
        window.dispatchEvent(new Event('resize'));
      },
    );
  }

  render() {
    const { editorState, initLoading, articleTitle } = this.state;
    return (
      <Spin spinning={initLoading} delay={100} tip="加载中...">
        {articleTitle ? (
          <div className="article-detail-title">{articleTitle}</div>
        ) : null}
        <Editor toolbarHidden={true} editorState={editorState} />
      </Spin>
    );
  }
}
